package erfgame.core.description.factory;

import java.util.Arrays;
import java.util.Comparator;
import java.util.ResourceBundle;

import erfgame.core.DescribedValue;
import erfgame.core.DescribedValueFactory;
import erfgame.core.Pair;

public class DoubleRangeDescribedValueFactory<ValueType> implements
		DescribedValueFactory<Double, ValueType> {
	
	private Pair<Double, String>[] descriptions;
	private Comparator<Object> comparator;
	private ResourceBundle resources;
	
	@SuppressWarnings("unchecked")
	public DoubleRangeDescribedValueFactory( ResourceBundle resources, Pair<Double, String>[] descriptions ) {
		this.descriptions = descriptions;
		this.resources = resources;
		this.comparator = new Comparator<Object>() {
			public int compare(Object o1, Object o2) {
				double d1 = ((Pair<Double, String>)o1).getFirst();
				double d2 = (Double)o2;
				if( d2 > d1 ) {
					return -1;
				} else if( d2 == d1 ) {
					return 0;
				} else {
					return 1;
				}
			}
		};
	}

	public DescribedValue<ValueType> describe(Double index, ValueType value) {
		// abuse the binary search operation
		int position = Arrays.binarySearch(this.descriptions, index, this.comparator);
		if( position < 0 ) {
			position = -position - 1;
		}
		if( position >= this.descriptions.length ) {
			// use the largest
			position --;
		}
		Pair<Double, String> description = this.descriptions[position];
		String key = description.getSecond();
		String text = resources.getString(key);
		return new DescribedValue<ValueType>(value, text);
	}
	

	
}
